package git.soulbgm.controller;

import git.soulbgm.common.base.BaseController;
import git.soulbgm.common.pojo.Response;
import git.soulbgm.service.TableBackupService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 数据库表的备份控制器
 *
 * @author SoulBGM
 * @date 2022-12-29
 */
@RestController
@RequestMapping("backup")
public class TableBackupController extends BaseController {

    private final TableBackupService service;

    /**
     * 日期时间格式化
     */
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public TableBackupController(TableBackupService service) {
        this.service = service;
    }

    /**
     * 获得需要备份的表名
     *
     * @return {@link Response}
     */
    @GetMapping("getBackupTableName")
    public Response getBackupTableName() {
        return success(service.getBackupTableName());
    }

    /**
     * 备份表数据
     *
     * @param response   响应
     * @param tableNames 表名,多个表名以逗号隔开
     * @throws IOException IO异常
     */
    @GetMapping("backupTableData")
    public void backupTableData(HttpServletResponse response, String tableNames) throws IOException {
        String nowDate = FORMATTER.format(LocalDateTime.now());
        String fileName = "数据库备份(" + nowDate + ").zip";
        fileName = new String(fileName.getBytes(Charset.forName("gb2312")), StandardCharsets.ISO_8859_1);
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        byte[] data = service.backupTableData(Arrays.stream(tableNames.split(",")).collect(Collectors.toList()));
        if (data != null) {
            response.addHeader("Content-Length", data.length + "");
            response.getOutputStream().write(data);
        }
    }

    /**
     * 恢复表数据
     *
     * @param file 文件
     * @throws IOException IO异常
     */
    @PostMapping("recoveryTableData")
    public Response recoveryTableData(MultipartFile file) throws IOException {
        service.recoveryTableData(file.getInputStream());
        return success("恢复成功");
    }

}
